/* __auth__ : KunLin */

package com.cskaoyan.lifecycle;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.bean.Goods;
import com.cskaoyan.bean.GoodsBak;
import com.cskaoyan.bean.GoodsExample;
import com.cskaoyan.mapper.GoodsElasticsearchMapper;
import com.cskaoyan.mapper.GoodsMapper;
import com.google.gson.Gson;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

@Component
public class ElasticsearchLifecycle implements SmartLifecycle {

    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    GoodsElasticsearchMapper gem;

    @Autowired
    RestHighLevelClient restHighLevelClient;

    Boolean running = false;

    @Autowired
    Gson gson;

    @Override
    public void start() {
        // 加载所有Goods的数据
        GoodsExample ge = new GoodsExample();
        ge.createCriteria().andDeletedEqualTo(false);
        List<Goods> goods = this.goodsMapper.selectByExample(ge);
        gem.saveAll(goods);


//        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(
//                RestClient.builder(
//                        new HttpHost("1.12.248.230", 9200, "http")));

        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("5m");
        List<GoodsBak> goodsBaks = goodsMapper.selectAllGoods();
        for (int i = 0; i < goodsBaks.size(); i++) {
            bulkRequest.add(new IndexRequest("goods_bak")
                    .source(JSON.toJSONString(goodsBaks.get(i)), XContentType.JSON));

        }
        BulkResponse bulk = null;
        try {
            bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(bulk.hasFailures());

//        try {
//            restHighLevelClient.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        this.running = true;
    }

    @Override
    public void stop() {

    }

//    @Override
//    public void stop(Runnable callback) {
//        callback.run();
//    }

    @Override
    public boolean isRunning() {
        return this.running;
    }
}
